import re
import time
from flask import request
from flask_restful import abort
from flask_login import current_user, login_user
from funcy import project
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import IntegrityError
from funcy import partial

from redash import models, limiter
from redash.permissions import (
    require_permission,
    require_admin_or_owner,
    is_admin_or_owner,
    require_permission_or_owner,
    require_admin_default,
)
from redash.handlers.base import (
    BaseResource,
    require_fields,
    get_object_or_404,
    paginate,
    order_results as _order_results,
)

from redash.authentication.account import (
    invite_link_for_user,
    send_invite_email,
    send_password_reset_email,
    send_verify_email,
)
from redash.settings import parse_boolean
from redash import settings

class TemplatesNewResource(BaseResource):
    def get(self):
        result = models.Templates.get_id()
        return result[0]

    @require_admin_default
    def post(self):
        req = request.get_json(force=True)
        require_fields(req, ("code","name"))
        templates = models.Templates(
        id =req["id"],
        org=self.current_org,
        userid = req["userid"],
        code = req["code"],
        name = req["name"],
        type =req["type"],
        orgunit_id =req["orgunit_id"],
        template =req["template"],
        is_active =req["is_active"],
        )
        try:
            models.db.session.add(templates)
            models.db.session.commit()
        except IntegrityError as e:
            if "code" in str(e):
                abort(400, message="编号已存在.")
            abort(500)

        # timeserial.record_event(
        #     {"action": "create", "object_id": timeserial.id, "object_type": "timeserial"}
        # )

class TemplatesResource(BaseResource):
    def get(self, templates_id):
        result = models.Templates.get_by_id(templates_id)
        return result.to_dict()

    @require_admin_default
    def post(self, templates_id):
        req = request.get_json(force=True)
        require_fields(req, ("code","name"))

        templates = models.Templates.get_by_id(templates_id)
        params = dict(userid=req["userid"],  code=req["code"],
                name=req["name"],type=req["type"],orgunit_id =req["orgunit_id"],
                template=req["template"],is_active=req["is_active"])

        try:
            self.update_model(templates, params)
            models.db.session.commit()
        except IntegrityError as e:
            if "code" in str(e):
                abort(400, message="编号已存在.")
            abort(500)

class TemplatesdeleteResource(BaseResource):
    @require_admin_default
    def post(self, templates_id):
        templates =  models.Templates.get_by_id(templates_id)
        result = models.Contracts.get_by_templateid(templates_id)
        if result.rowcount > 0 :
            abort(400, message="模板已使用，不能删除！")
            return
        models.db.session.delete(templates)
        models.db.session.commit()
        # if result > 0 :
        #     abort(400, message="模板已使用，不能删除！")
        #     return



class TemplatesListResource(BaseResource):
    def post(self):
        req = request.get_json(force=True)
        page = req["page"]
        page_size = req["pagesize"]
        code = req["code"]
        name = req["name"]
        type = req["type"]
        orgunitname = req["orgunitname"] if "orgunitname" in req else ""
        orgunit_id = req["orgunit_id"] if "orgunit_id" in req else 0
        orderfield = req["field"] if "field" in req else ""
        if orderfield=="code":
            orderfield ="t1.code"
        elif orderfield=="name":
            orderfield ="t1.name"
        elif orderfield=="typename":
            orderfield ="t4.typename"
        elif orderfield=="orgunitname":
            orderfield ="t5.name"
        else:
            orderfield ="t1.code"
        order = req["order"] if "order" in req else 0

        strwhere ="t1.org_id=" +str(self.current_org.id)
        if code !="" :
            strwhere = strwhere + " and t1.code like '%"+code+"%'"
        if name !='' :
            strwhere = strwhere + " and t1.name like '%"+name+"%'"
        if type !='' :
            strwhere = strwhere + " and  ('"+type+"' = ANY(t1.type) or t1.id<=1)"
        if orgunitname !='' :
            strwhere = strwhere + " and (t5.name like '%"+orgunitname+"%' or t1.id<=1)"
        if orgunit_id>0 :
            strwhere = strwhere + " and  (t1.orgunit_id="+str(orgunit_id)+" or t1.id<=1)"

        strgetfield =""" t1.*,t4.typename,COALESCE(t5.name,'') as orgunitname """

        tblname = """public.templates t1 left join public.contracttypeview t4 on t1.type =t4.type  and t1.org_id=t4.org_id
        left join public.orgunit t5 on t1.orgunit_id=t5.id """
        #orderfield ="t1.type,t1.code"
        result = models.ContractApply.get_pagequery(tblname,strgetfield,orderfield,page_size,page,order,strwhere)
        return result[0]

class TemplatestypeListResource(BaseResource):
    def post(self):
        req = request.get_json(force=True)
        page = req["page"]
        page_size = req["pagesize"]
        code = req["code"]
        strwhere ="t1.org_id=" +str(self.current_org.id)
        if code !='' :
            strwhere = strwhere + " and  t1.typecode = '"+code+"'"
        strgetfield =""" t1.*"""
        tblname = """public.contracttypeview t1 """
        orderfield ="t1.typecode"
        result = models.ContractApply.get_pagequery(tblname,strgetfield,orderfield,page_size,page,0,strwhere)
        return result[0]
